const _ = require('lodash');
const foodItemFacade = require('../../app/facade/foodItem.server.facade.js');

module.exports = {
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    addFoodItem : addFoodItem,
    delFoodItem : delFoodItem,
    getFoodItems : getFoodItems,
    getFoodItemByNameAndProducer : getFoodItemByNameAndProducer
}

function getFoodItemByName(req, res, next) {
    let params = req.params;
    let name = params.name;
    if (_.isEmpty(name)) {
        return next(new Error('food name is empty'));
    } else {
    foodItemFacade.getFoodItemByName(name, (error, result) => {
        if (error) {
            return next(new Error(error));
        } else {
            //return res.json(result);
            res.render('foodItem', result);
        }
    });
    }
}


function getFoodItemByProducer(req, res, next){
    let params = req.params;
    let producer = params.producer;
    if(_.isEmpty(producer)){
        return next(new Error("Producer is empty"))
    }else{
        foodItemFacade.getFoodItemByProducer(producer, (error, result) => {
            if(error){
                return next(new Error(error));
            }else{
                return res.json(result);
            }
        });
    }
}

function addFoodItem(req, res, next){
    let body = req.body;
    foodItemFacade.addFoodItem(body);
}


function delFoodItem(req, res, next){
    let itemId = req.params.itemId;
    foodItemFacade.delFoodItem(itemId);
}

function getFoodItems(req, res, next){
    foodItemFacade.getFoodItems((error, result) => {
        if(error){
            return next(new Error(error));
        }else{
            return res.json(result);
        }

    });
}

function getFoodItemByNameAndProducer(req, res, next){
    let body = req.body;
    let name = body.name;
    let producer = body.producer;

    if(_.isEmpty(name) || _.isEmpty(producer)){
        return next(new Error("Name or Producer is empty"));
    }else{
        foodItemFacade.getFoodItemByNameAndProducer(name, producer, (error, result)=>{
            if(error){
                return next(new Error(error));
            }else{
                res.json(result);
            }
        });
    }
};

